package com.sharding.order.repository;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sharding.order.domain.dto.OrderItemDetailDto;
import com.sharding.order.domain.entity.OrderInfo;
import com.sharding.order.domain.entity.OrderItemDetail;
import com.sharding.order.domain.query.OrderInfoBaseQuery;
import com.sharding.order.domain.vo.OrderDetailVO;
import com.sharding.order.domain.vo.OrderInfoVO;
import com.sharding.order.mapper.MerchantOrderInfoMapper;
import com.sharding.order.mapper.MerchantOrderItemDetailMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * @author ruyuan
 * @Description
 */
@Repository
public class MerchantOrderRepository {
    @Autowired
    private MerchantOrderInfoMapper merchantOrderInfoMapper;
    @Autowired
    private MerchantOrderItemDetailMapper merchantOrderItemDetailMapper;

    /**
     * 查询订单列表
     *
     * @param orderInfoBaseQuery 入参
     * @return 出参
     */
    public Page<OrderInfoVO> queryOrderInfoList(OrderInfoBaseQuery orderInfoBaseQuery) {
        //1.组装mybatis查询插件
        Page<OrderInfoVO> page = new Page<>();
        page.setCurrent(orderInfoBaseQuery.getPageNo());
        page.setSize(orderInfoBaseQuery.getPageSize());
        // 2.查询该用户订单信息
        return merchantOrderInfoMapper.queryOrderInfoList(page, orderInfoBaseQuery);
    }

    /**
     * 根据订单号查询订单明细
     *
     * @param orderNo 入参
     * @return 出参
     */
    public OrderDetailVO getOrderDetail(String orderNo) {
        //1.查询订单基础信息
        OrderDetailVO orderDetailVO = merchantOrderInfoMapper.getOrderInfoByNo(orderNo);
        //2.判断订单是否为空
        if (Objects.isNull(orderDetailVO)) {
            return null;
        }
        // 3.根据订单号查询出所有的订单详细信息
        List<OrderItemDetailDto> orderItemDetailList = merchantOrderItemDetailMapper.getOrderItemDetailList(orderNo);
        //4.返回结果集设置订单详情信息
        orderDetailVO.setOrderItemDetails(orderItemDetailList);
        return orderDetailVO;
    }

    /**
     * 插入订单信息
     *
     * @param orderInfo 入参
     */
    @Transactional(rollbackFor = Exception.class)
    public void syncOrderInfo(OrderInfo orderInfo, List<OrderItemDetail> orderItemDetailList) {
        //1.保存订单信息
        merchantOrderInfoMapper.insertSelective(orderInfo);
        //2.批量保存订单明细
        merchantOrderItemDetailMapper.batchInsert(orderItemDetailList);
    }

    /**
     * 接受订单
     *
     * @param orderNo
     */
    public void receiveOrder(String orderNo, Integer status) {
        merchantOrderInfoMapper.receiveOrder(orderNo, status);
    }

    /**
     * 修改订单状态
     */
    public void updateStatus(String orderNo, Integer status) {
        merchantOrderInfoMapper.updateStatus(orderNo, status);
    }


}
